<?php

if (!defined('IN_SEXMALL'))
{
	die('Hacking attempt');
}


/**
 * 验证输入的邮件地址是否合法
 *
 * @access  public
 * @param   string      $email      需要验证的邮件地址
 *
 * @return bool
 */
function is_email($user_email)
{
	$chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
	if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false)
	{
		if (preg_match($chars, $user_email))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

/**
 *
 * 验证输入的电话号码是否合法
 *
 * @param unknown $user_phone
 * @return boolean
 */
function is_mobilephone($user_phone)
{
	$pattern = '/((^\d{11}$)|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/i';
	return preg_match($pattern, $user_phone);
}

/**
 * 检查是否为一个合法的时间格式
 *
 * @access  public
 * @param   string  $time
 * @return  void
 */
function is_time($time)
{
	$pattern = '/[\d]{4}-[\d]{1,2}-[\d]{1,2}\s[\d]{1,2}:[\d]{1,2}:[\d]{1,2}/';

	return preg_match($pattern, $time);
}


/**
 * 格式化商品价格
 *
 * @access  public
 * @param   float   $price  商品价格
 * @return  string
 */
function price_format($price, $change_price = true)
{
	if($price==='')
	{
		$price=0;
	}
	if ($change_price && defined('WAP_ADMIN') === false)
	{
		switch ($GLOBALS['_CFG']['price_format'])
		{
			case 0:
				$price = number_format($price, 2, '.', '');
				break;
			case 1: // 保留不为 0 的尾数
				$price = preg_replace('/(.*)(\\.)([0-9]*?)0+$/', '\1\2\3', number_format($price, 2, '.', ''));

				if (substr($price, -1) == '.')
				{
					$price = substr($price, 0, -1);
				}
				break;
			case 2: // 不四舍五入，保留1位
				$price = substr(number_format($price, 2, '.', ''), 0, -1);
				break;
			case 3: // 直接取整
				$price = intval($price);
				break;
			case 4: // 四舍五入，保留 1 位
				$price = number_format($price, 1, '.', '');
				break;
			case 5: // 先四舍五入，不保留小数
				$price = round($price);
				break;
		}
	}
	else
	{
		$price = number_format($price, 2, '.', '');
	}

	return sprintf($GLOBALS['_CFG']['currency_format'], $price);
}


/**
 *  清除指定后缀的模板缓存或编译文件
 *
 * @access  public
 * @param  bool       $is_cache  是否清除缓存还是清出编译文件
 * @param  string     $ext       需要删除的文件名，不包含后缀
 *
 * @return int        返回清除的文件个数
 */
function clear_tpl_files($is_cache = true, $ext = '')
{
	$dirs = array();

	if (isset($GLOBALS['shop_id']) && $GLOBALS['shop_id'] > 0)
	{
		$tmp_dir = DATA_DIR ;
	}
	else
	{
		$tmp_dir = 'temp';
	}

	// 清除缓存文件
	if ($is_cache)
	{
		$folder = opendir(TEMP_DIR);
		while ($dir = readdir($folder))
		{
			if ($dir == '.' || $dir == '..' || $dir == 'index.htm' || $dir == 'index.html')
			{
				continue;
			}

			if (in_array($dir, array('default', 'touch', 'pad')))
			$cache_dir[] = TEMP_DIR . $dir .'/caches/';
			$dirs[] = TEMP_DIR . 'query_caches/';
			$dirs[] = TEMP_DIR . 'static_caches/';
		}

		foreach ($cache_dir as $val)
		{
			for($i = 0; $i < 16; $i++)
			{
				$hash_dir = $val . dechex($i);
				$dirs[] = $hash_dir . '/';
			}
		}
	}
	// 清除编译文件
	else
	{
		$folder = opendir(TEMP_DIR);
		while ($dir = readdir($folder))
		{
			if ($dir == '.' || $dir == '..' || $dir == 'index.htm' || $dir == 'index.html')
			{
				continue;
			}

			if (in_array($dir, array('default', 'touch', 'pad')))
			$dirs[] = TEMP_DIR . $dir .'/compiled/';
		}
	}

	$str_len = strlen($ext);
	$count   = 0;

	foreach ($dirs AS $dir)
	{
		$folder = @opendir($dir);

		if ($folder === false)
		{
			continue;
		}

		while ($file = readdir($folder))
		{
			if ($file == '.' || $file == '..' || $file == 'index.htm' || $file == 'index.html')
			{
				continue;
			}
			if (is_file($dir . $file))
			{
				/* 如果有文件名则判断是否匹配 */
				$pos = ($is_cache) ? strrpos($file, '_') : strrpos($file, '.');

				if ($str_len > 0 && $pos !== false)
				{
					$ext_str = substr($file, 0, $pos);

					if ($ext_str == $ext)
					{
						if (@unlink($dir . $file))
						{
							$count++;
						}
					}
				}
				else
				{
					if (@unlink($dir . $file))
					{
						$count++;
					}
				}
			}
		}
		closedir($folder);
	}

	return $count;
}

/**
 * 清除模版编译文件
 *
 * @access  public
 * @param   mix     $ext    模版文件名， 不包含后缀
 * @return  void
 */
function clear_compiled_files($ext = '')
{
	return clear_tpl_files(false, $ext);
}

/**
 * 清除缓存文件
 *
 * @access  public
 * @param   mix     $ext    模版文件名， 不包含后缀
 * @return  void
 */
function clear_cache_files($ext = '')
{
	return clear_tpl_files(true, $ext);
}

/**
 * 清除模版编译和缓存文件
 *
 * @access  public
 * @param   mix     $ext    模版文件名后缀
 * @return  void
 */
function clear_all_files($ext = '')
{
	return clear_tpl_files(false, $ext) + clear_tpl_files(true,  $ext);
}

/**
 * 页面上调用的js文件
 *
 * @access  public
 * @param   string      $files
 * @return  void
 */
function smarty_insert_scripts($args)
{
	static $scripts = array();

	$arr = explode(',', str_replace(' ','',$args['files']));

	$str = '';
	foreach ($arr AS $val)
	{
		if (in_array($val, $scripts) == false)
		{
			$scripts[] = $val;
			if ($val{0} == '.')
			{
				$str .= '<script type="text/javascript" src="' . $val . '"></script>';
			}
			else
			{
				$str .= '<script type="text/javascript" src="js/' . $val . '"></script>';
			}
		}
	}

	return $str;
}

/**
 * 创建分页的列表
 *
 * @access  public
 * @param   integer $count
 * @return  string
 */
function smarty_create_pages($params)
{
	extract($params);

	$str = '';
	$len = 10;

	if (empty($page))
	{
		$page = 1;
	}

	if (!empty($count))
	{
		$step = 1;
		$str .= "<option value='1'>1</option>";

		for ($i = 2; $i < $count; $i += $step)
		{
			$step = ($i >= $page + $len - 1 || $i <= $page - $len + 1) ? $len : 1;
			$str .= "<option value='$i'";
			$str .= $page == $i ? " selected='true'" : '';
			$str .= ">$i</option>";
		}

		if ($count > 1)
		{
			$str .= "<option value='$count'";
			$str .= $page == $count ? " selected='true'" : '';
			$str .= ">$count</option>";
		}
	}

	return $str;
}

/**
 * 调用array_combine函数
 *
 * @param   array  $keys
 * @param   array  $values
 *
 * @return  $combined
 */
if (!function_exists('array_combine')) {
	function array_combine($keys, $values)
	{
		if (!is_array($keys)) {
			user_error('array_combine() expects parameter 1 to be array, ' .
			gettype($keys) . ' given', E_USER_WARNING);
			return;
		}

		if (!is_array($values)) {
			user_error('array_combine() expects parameter 2 to be array, ' .
			gettype($values) . ' given', E_USER_WARNING);
			return;
		}

		$key_count = count($keys);
		$value_count = count($values);
		if ($key_count !== $value_count) {
			user_error('array_combine() Both parameters should have equal number of elements', E_USER_WARNING);
			return false;
		}

		if ($key_count === 0 || $value_count === 0) {
			user_error('array_combine() Both parameters should have number of elements at least 0', E_USER_WARNING);
			return false;
		}

		$keys    = array_values($keys);
		$values  = array_values($values);

		$combined = array();
		for ($i = 0; $i < $key_count; $i++) {
			$combined[$keys[$i]] = $values[$i];
		}

		return $combined;
	}
}

/**
 *  分页
 * $num 记录总数
 * $perpage 每页数
 * $curpage 当前页
 * $mpurl 分页链接
 */
function simplepage($num, $perpage, $curpage, $mpurl, $params=array(),$rewrite=true) {
	$return = '<form method="post" action="">';
	$return .= '<span class="page_info">共'.$num.'条/共'.ceil($num/$perpage).'页</span>';

	$next = $prev = '';
	$isNext = false;
	if ($num > $curpage * $perpage){
		$isNext = true;
		$params['curpage'] += 1;
		if ($rewrite)
		$next = '&nbsp;<a href="'.$mpurl.'-'.implode('-',$params).'.html" class="nxt">[下页]</a>&nbsp;';
		else{
			$params2 = array();
			foreach ($params AS $key => $val){
				$params2[] = $key .'='. $val;
			}
			$next = '&nbsp;<a href="'.$mpurl.'.php?'.implode('&',$params2).'" class="nxt">[下页]</a>&nbsp;';
		}

	}
	if ($curpage > 1){
		$params['curpage'] -= 1;
		$isNext && $params['curpage'] -= 1;	// 如果有下一页，刚上一页要多减一页

		if ($rewrite)
		$prev = '<a href="'.$mpurl.'-'.implode('-',$params).'.html">[上页]</a>&nbsp;';
		else{
			$params2 = array();
			foreach ($params AS $key => $val){
				$params2[] = $key .'='. $val;
			}
			$prev = '<a href="'.$mpurl.'.php?'.implode('&',$params2).'" class="nxt">[上页]</a>&nbsp;';
		}
	}

	if($next || $prev) {
		$return .= '<p>'.$prev.'当前第'.$curpage.'页'.''.$next.'</p>';
	}

	(ceil($num/$perpage) > 1) &&
	$return .='<p style="padding-top:3px;">第<input type="text" value="" name="page" size="4">页' .
			'<input type="submit" value="跳转" class=""></p></form>';

	return $return;
}



/**
 *  设置cookie
 *
 * @access  public
 * @param
 *
 * @return void
 */
function set_cookie($username='', $password='' ,$remember= null )
{
	$now = local_time();
	if (empty($username) || empty($password))
	{
		/* 摧毁cookie */
		foreach ($_COOKIE["WAP"] AS $key => $val){
			// 不删除持久分仓、pad提示、版本选择、列表显示、高清cookie
			if (!in_array($key, array('p_wh', 'pad_tip', 'revision', 'show', 'hd'))){
				wap_setcookie("WAP[$key]", '');
			}
		}
	}
	else if (!empty($username) && !empty($password) && $remember)
	{
		/* 设置cookie */
		$time = $now + 3600 * 24 * COOKIE_EXPIRE;

		$str = substr(md5(AUTH_KEY), -8);
		$auth_str = encrypt($str, AUTH_KEY);
		$auth = encrypt($username, AUTH_KEY).':'.$auth_str;

		wap_setcookie("WAP[auth]", $auth, $time);
		wap_setcookie("WAP[auth$str]", encrypt($password, AUTH_KEY), $time);

	}
	else if (!empty($username) && !empty($password))
	{
		$str = substr(md5(AUTH_KEY), -8);
		$auth_str = encrypt($str, AUTH_KEY);
		$auth = encrypt($username, AUTH_KEY).':'.$auth_str;
		wap_setcookie("WAP[auth]", $auth, -1);
	}
}

/**
 *  设置指定用户SESSION
 *
 * @access  public
 * @param
 *
 * @return void
 */
function set_session($username='', $user_token='')
{
	global $mem;

	if (empty($username) || empty($user_token))
	{
		// 销毁 memcache
		$mem->del('user_token');
		$mem->del('username');
		$mem->del('back_act');
		$mem->del('address_id');
	}
	else
	{
		// 设置 memcache
		$mem->addCache('user_token', $user_token);
		$mem->addCache('username', $username);
	}
}

/**
 * 取得 中文星期几
 */
function weekday($week)
{
	$week = intval($week);

	$ch_week = '';

	switch ($week)
	{
		case 1:
			$ch_week = '星期一';
			break;
		case 2:
			$ch_week = '星期二';
			break;
		case 3:
			$ch_week = '星期三';
			break;
		case 4:
			$ch_week = '星期四';
			break;
		case 5:
			$ch_week = '星期五';
			break;
		case 6:
			$ch_week = '星期六';
			break;
		case 7:
			$ch_week = '星期日';
			break;
	}

	return $ch_week;
}


/**
 * 记录COOKIE
 * @param	int		$expire		cookie过期时间，<0为会话cookie
 */
function wap_setcookie($key='', $value='', $expire=0, $prefix=true)
{
	if(empty($key))return false;

	$now = local_time();

	if ($expire == 0)
	{
		$time = $now + 3600 * 24 * COOKIE_EXPIRE;
	}
	else if ($expire > 0){
		$time = $now + $expire;
	}
	else
	{
		$time = 0;
	}

	if($prefix && !preg_match("/\[.*?\]/", $key) && stristr($key,'WAP_') === FALSE)
	{
		$key = COOKIE_PREFIX . $key;
	}

	if ($key && $value)
	{
		setcookie($key, $value, $time, COOKIE_PATH, COOKIE_DOMAIN);
	}
	else if ($key)
	{
		setcookie($key, '', $now - 86400, COOKIE_PATH, COOKIE_DOMAIN);
	}
	else
	{
		return false;
	}
}

/**
 * 获取COOKIE值
 */
function wap_getcookie($key, $prefix=true)
{
	if ( empty($key)){
		return false;
	}

	$value = false;

	/* 二维 */
	if (preg_match("/\[.*?\]/", $key))
	{
		$posL = strrpos($key, '[');
		$posR = strrpos($key, ']');
		$oneDim = substr($key, 0, $posL);
		$twoDim = substr($key, $posL + 1, $posR - $posL - 1);

		$value = !empty($_COOKIE[$oneDim][$twoDim]) ? $_COOKIE[$oneDim][$twoDim] : null;
	}
	/* 一维 */
	else //if (!empty($_COOKIE[$key]))
	{
		if($prefix && stristr($key,'WAP_')=== FALSE){
			$key = COOKIE_PREFIX.$key;
		}

		$value = empty($_COOKIE[$key]) ? null : $_COOKIE[$key];
	}

	return $value;
}



/*
 * 判断是否AJAX 请求
 */
function isAjax()
{
	if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) ) {
		if('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH']))
		return true;
	}
	return false;
}



/**
 * 取得用户 token
 */
function get_user_token()
{
	$user_token = MInterface::$user_token;
	$username = MInterface::$login_id;

	if (empty($username)){
		$auth = wap_getcookie("WAP[auth]");
		list($username, $auth_str) = explode(':', $auth);
		$username = decrypt($username, AUTH_KEY);
	}

	if (empty($user_token)){
		$user_token = wap_getcookie("WAP[auth_token]");
		$user_token = decrypt($user_token, AUTH_KEY);
	}


	if (empty($user_token) || empty($username))
	{
		return false;
	}

	return $user_token;
}

/**
 * 获取用户名
 */
function get_username()
{
	$username = MInterface::$login_id;

	if (empty($username)){
		$auth = wap_getcookie("WAP[auth]");
		list($username, $auth_str) = explode(':', $auth);
		$username = decrypt($username, AUTH_KEY);
	}

	return $username;
}


/**
 * 载入配置信息
 *
 * @access  public
 * @return  array
 */
function load_config()
{
	$arr = array();

	$data = read_static_cache('shop_config', 86400, 1, true);
	if ($data === false)
	{
		$sql = 'SELECT code, value FROM ' . TABLEPRE . 'shop_config WHERE parent_id > 0';
		$res = $GLOBALS['db']->getAll($sql);

		foreach ($res AS $row)
		{
			$arr[$row['code']] = $row['value'];
		}

		/* 对数值型设置处理 */
		$arr['cache_time']           = intval($arr['cache_time']);
		$arr['top10_time']           = intval($arr['top10_time']);
		$arr['hash_code']            = md5(AUTH_KEY);

		if (!isset($GLOBALS['_CFG']['ecs_version']))
		{
			/* 如果没有版本号则默认为2.0.5 */
			$GLOBALS['_CFG']['wap_version'] = 'v2.0.5';
		}

		//限定语言项
		$lang_array = array('zh_cn', 'zh_tw', 'en_us');
		if (empty($arr['lang']) || !in_array($arr['lang'], $lang_array))
		{
			$arr['lang'] = 'zh_cn'; // 默认语言为简体中文
		}

		write_static_cache('shop_config', $arr, true);
	}
	else
	{
		$arr = $data;
	}

	return $arr;
}



/**
 * 获取邮件模板
 *
 * @access  public
 * @param:  $tpl_name[string]       模板代码
 *
 * @return array
 */
function get_mail_template($tpl_name)
{
	$sql = 'SELECT template_subject, is_html, template_content FROM ' . TABLEPRE.'mail_templates' . " WHERE template_code = '$tpl_name'";

	return $GLOBALS['db']->GetRow($sql);
}


/**
 * 计算订单运费
 */
function shipping_fee($total)
{
	$total['carriage'] = 0;

	// 满x元免邮
	if (defined('FREE_CARRIAGE_TYPE') && FREE_CARRIAGE_TYPE == 1)
	{
		if (($total['amount'] > 0) && ($total['amount'] - $total['favourable_money'] - $total['ex_fav_money'] < FREE_CARRIAGE_MONEY))
		{
			$total['carriage'] = SHIPPING_FEE;
		}
	}
	// 满x件免邮
	else if (defined('FREE_CARRIAGE_TYPE') && FREE_CARRIAGE_TYPE == 2)
	{
		// 检查数量
		if (($total['count'] > 0 && $total['count'] < FREE_CARRIAGE_COUNT && $total['amount'] - $total['favourable_money'] - $total['ex_fav_money'] < BASE_FREE_CARRIAGE))
		{
			$total['carriage'] = SHIPPING_FEE;
		}
	}
	else
	{
		//$total['carriage'] = SHIPPING_FEE;
		if ($total['amount'] > 0 && $total['amount'] - $total['favourable_money'] - $total['ex_fav_money'] < FREE_CARRIAGE_MONEY)
		{
			$total['carriage'] = SHIPPING_FEE;
		}
	}


	/* 计算还剩x元/件即免邮 */
	if ($total['carriage'])
	{
		$total['free_carriage'] = 0;
		if (defined('FREE_CARRIAGE_TYPE') && FREE_CARRIAGE_TYPE == 1){
			$total['free_carriage'] = (FREE_CARRIAGE_MONEY - $total['amount'] - $total['favourable_money'] - $total['ex_fav_money']) . '元';
		}
		else if (defined('FREE_CARRIAGE_TYPE') && FREE_CARRIAGE_TYPE == 2){
			$total['free_carriage'] = (FREE_CARRIAGE_COUNT - $total['count']) . '件';
		}
		else {
			$total['free_carriage'] = abs(FREE_CARRIAGE_MONEY - ($total['amount'] - $total['favourable_money'] - $total['ex_fav_money'])) . '元';
		}
	}

	return array('carriage'=>$total['carriage'], 'free_carriage'=>$total['free_carriage']);
}


/**
 * 商品统计(用户商品行为)
 * 用户行为：加入购物袋, 关注(收藏、喜欢)
 * @param	array	$arr	(频道ID,品牌ID,品牌名称,产品ID,产品名称,产品分类,分仓,产品图,售价,市场价,折扣,库存)
 * @param	int		$type	1:加入购物袋; 2:关注
 */
function user_product_action($arr, $type)
{
	global $mem, $mInterface, $db;

	$now = local_time();

	$sql = "SELECT id, addnum FROM ".TABLEPRE. "ranking WHERE product_id='".$arr['product_id']."'";
	$result = $db->getRow($sql);

	// 商品存在则更新
	if (!empty($result))
	{
		$data = array(
			'addnum'	=> $result['addnum'] + 1,
			'updtime'	=> $now
		);

		if ($type == 1){
			$data['leavings'] = $arr['leavings'];
		}

		$db->autoExecute(TABLEPRE."ranking", $data, 'UPDATE', 'product_id='.$arr['product_id']);
		$rid = $result['id'];
	}
	// 插入
	else
	{
		$brand = get_brand($arr['brand_id']);

		$data = array(
			'channel_id'		=> $arr['channel_id'],
			'product_id'		=> $arr['product_id'],
			'brand_id'			=> $brand['brand_id'],
			'brand_name'		=> $brand['brand_name'],
			'product_cat_id'	=> $arr['cat_id'],
			'warehouse'			=> $arr['warehouse'],
			'product_name'		=> $arr['product_name'],
			'small_image'		=> $arr['small_image'],
			'sexmall_price'		=> $arr['sexmall_price'],
			'market_price'		=> $arr['market_price'],
			'agio'				=> $arr['agio'],
			'leavings'			=> $arr['leavings'],
			'addtime'			=> $now,
			'updtime'			=> $now,
			'addnum'			=> 1
		);

		$db->autoExecute(TABLEPRE."ranking", $data);

		$rid = $db->insert_id();
	}

	// 记录用户行为
	if ($rid)
	{
		$username = get_username();

		$data = array(
			'username'	=> $username,
			'rid'		=> $rid,
			'type'		=> intval($type),
			'add_time'	=> $now
		);

		$query = $db->autoExecute(TABLEPRE."user_action", $data);
	}

	return $query;
}


/**
 * 计算各状态订单数量
 */
function calculate_order_num($orders)
{
	if (empty($orders) || !is_array($orders)){
		return false;
	}

	$now = local_time();

	$order_num = array('unpay'=>0, 'unverify'=>0, 'unsend'=>0, 'sended'=>0);
	foreach ((array)$orders AS $key => $val)
	{
		if (!is_array($val)){
			unset($orders[$key]);
			continue;
		}

		if ($val['order_status'] == 0)
		{
			$order_num['unpay']++;
		}
		else if ($val['order_status'] == 1
		|| ($now - $val['add_time'] < 3600  && $val['order_status'] == 10))
		{
			$order_num['unverify']++;
		}
		else if ($val['order_status'] == 20	|| $val['order_status'] == 10
		|| $val['order_status'] == 21)
		{
			$order_num['unsend']++;
		}
		else if ($val['order_status'] == 22 || $val['order_status'] == 44)
		{
			$order_num['sended']++;
		}
	}

	return $order_num;
}


/**
 * 获取可评价的订单状态
 * @param	$key
 * @return	array
 */
function get_order_feedback_status(){
	$order_status = array('22','25','53','54','49');
	return $order_status;
}

?>